<template>
    <view>
        <!-- index.wxml -->
        <view class="top">
            <view class="banner">
                <swiper autoplay indicator-dots>
                    <block v-for="(item, index) in bannershowlist" :key="index">
                        <swiper-item>
                            <image :src="item.imgUrl" mode="widthFix"></image>
                        </swiper-item>
                    </block>
                </swiper>
            </view>
        </view>
        <view class="top-search">
            <view class="left">
                <view class="label" @tap="goLocation">
                    <text>{{ cityName }}</text>
                    <i></i>
                </view>
                <input class="input" type="text" :placeholder="isMap ? '搜索位置查找附近门店' : '搜索门店'" :value="name" @input="onInputChange" />
            </view>
            <view v-if="isMap" class="right" @tap="goListSeach">
                <view class="iconfont icon-list"></view>
                <text>列表</text>
            </view>
            <view v-else class="right" @tap="goMapSeach">
                <!-- <button hover-class="button-click"  class="iconfont icon-map" bindgetphonenumber="phone" open-type="getPhoneNumber">地图</button> -->
                <view class="iconfont icon-map"></view>
                <text>地图</text>
            </view>
        </view>
        <view class="container">
            <!-- 地图 -->
            <view class="mapPage" v-if="isMap">
                <!-- 点击marker展示门店 -->
                <view class="list" v-if="store">
                    <view class="item" @tap="goStore" :data-storeid="store.storeId">
                        <view v-if="item.headImg">
                            <image class="img" :src="item.headImg" mode="scaleToFill"></image>
                        </view>
                        <view v-else>
                            <image class="img" src="/static/logo.png" mode="aspectFit"></image>
                        </view>
                        <view class="info">
                            <view class="name">{{ store.storeName }}</view>
                            <view class="tag-primary">
                                <text class="distance">{{ store.distance }}</text>
                                km
                            </view>
                            <view class="iconfont icon-weizhi btn" @tap.stop.prevent="goTencentMap" :data-info="store"></view>
                            <view class="iconfont icon-phone btn" @tap.stop.prevent="call" :data-info="store.kefuPhone"></view>
                        </view>
                        <view class="address">
                            {{ store.address }}
                        </view>
                    </view>
                </view>
                <map class="map" id="map" :longitude="lon" :latitude="lat" scale="10" :show-location="true" :markers="markers" @markertap="makertap"></map>
            </view>
            <!-- 列表 -->
            <view class="lists" v-else-if="">
                <view class="list">
                    <block v-if="MainStorelist.length > 0">
                        <view class="item" @tap="goStore" :data-storeid="item.storeId" v-for="(item, index) in MainStorelist" :key="index">
                            <view v-if="item.headImg">
                                <image class="img" :src="item.headImg" mode="scaleToFill"></image>
                            </view>

                            <view v-else>
                                <image class="img" src="/static/logo.png" mode="aspectFit"></image>
                            </view>

                            <view class="info">
                                <view class="name">{{ item.storeName }}</view>
                                <view class="iconfont icon-weizhi btn" @tap.stop.prevent="goTencentMap" :data-info="item"></view>
                                <view class="iconfont icon-phone btn" @tap.stop.prevent="call" :data-info="item.kefuPhone"></view>
                                <view class="tag-primary" v-if="item.distance">
                                    <text class="distance">{{ item.distance }}</text>
                                    km
                                </view>
                            </view>

                            <view class="address">
                                {{ item.address }}
                            </view>
                        </view>
                    </block>
                    <block v-else>
                        <view>
                            <view class="noStoreInfo" @tap="goUser">- 暂无门店 -</view>
                            <!-- <button bind:tap="goUser" class="noStoreBtn">个人中心</button> -->
                        </view>
                    </block>
                </view>
            </view>
        </view>
        <!-- 右侧快捷入口 -->
        <view class="quickBtns">
            <view class="btn bg-primary door" @tap="openDoor">
                <view class="item">
                    <view class="iconfont icon-door-open"></view>
                    <view class="text">开门</view>
                </view>
            </view>
            <navigator class="btn color-primary help" url="../help/help">
                <view class="item">
                    <view class="iconfont icon-help"></view>
                    <view class="text">帮助</view>
                </view>
            </navigator>
        </view>
        <!-- 底部按钮 -->
        <view v-if="isMap" class="bg-primary enterBtn" @tap="goListSeach">预定房间</view>
        <view class="bt"></view>
    </view>
</template>

<script>
// index.js
// 获取应用实例
const app = getApp();
var http = require('../../utils/http');
var util1 = require('../../utils/util.js');
export default {
    data() {
        return {
            appName: app.globalData.appName,
            statusBarHeight: '',
            titleBarHeight: '',
            isMap: false,
            bannershowlist: [],

            //banner数组
            MainStorelist: [],

            //列表数组
            cityName: '选择城市',

            name: '',

            //搜索关键词
            lat: '',

            lon: '',
            markers: [],

            store: {
                storeId: '',
                storeName: '',
                distance: '',
                kefuPhone: '',
                address: ''
            },

            //地图上方展示的门店详情
            storeId: '',

            // isLogin:app.globalData.isLogin,
            pageindex: 1,

            //分页的page
            canLoadMore: true,

            //是否还能加载更多
            //管理员代下单用户id
            userId: '',

            orderlist: []
        };
    }
    /**
     * 生命周期函数--监听页面显示
     */,
    onShow() {},
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {},
    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {
        let that = this;
        if (that.canLoadMore) {
            that.pageindex++;
            this.getMainListdata();
        } else {
            uni.showToast({
                title: '没有更多门店了...',
                icon: 'none'
            });
        }
    },
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {
        let that = this;
        return {
            title: that.appName,
            path: '/pages/index/index',
            success: function (res) {
                // 转发成功
                uni.showToast({
                    title: '分享成功',
                    icon: 'success',
                    duration: 2000
                });
            },
            fail: function (res) {
                // 分享失败
            }
        };
    },
    onLoad(options) {
        this.userId = options.userId ? parseInt(options.userId) : '';
        var that = this;
        if (options.storeId) {
            that.setData({
                storeId: options.storeId
            });
        }
        this.setData({
            statusBarHeight: uni.getStorageSync('statusBarHeight'),
            titleBarHeight: uni.getStorageSync('titleBarHeight')
            // cityName: wx.getStorageSync('cityName') ? wx.getStorageSync('cityName') : ''
        });

        that.getLocation();
        that.getBannerdata();
        // that.getMainListdata('refresh');
        // 实例化API核心类
        // qqmapsdk = new QQMapWX({
        //   key: 'FQGBZ-OY4CQ-XM35H-BWLYV-2U2V2-SRBZ6'
        // });
    },
    methods: {
        goStore(e) {
            var storeId = e.currentTarget.dataset.storeid;
            console.log('门店选择页面的id=' + storeId);
            if (storeId) {
                // 设置参数
                uni.setStorageSync('global_store_id', storeId);
            }
            uni.switchTab({
                url: '/pages/index/index'
            });
        },

        goLocation() {
            var that = this;
            uni.navigateTo({
                url: '../location/location',
                events: {
                    // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
                    pageDataList: function (data) {
                        console.log('页面B触发事件时传递的数据1：',data)
                        that.setData({
                            cityName: data
                        });
                        // wx.setStorageSync('cityName', data)
                        that.getLocation();
                        // that.getBannerdata();
                        that.getMainListdata('refresh');
                    }
                }
            });
        },

        //点击地图
        goMapSeach() {
            this.setData({
                isMap: true
            });
            this.setData({
                name: ''
            });
            this.getMainListdata('refresh');
        },

        goListSeach() {
            this.setData({
                isMap: false
            });
            this.setData({
                name: ''
            });
            this.getMainListdata('refresh');
        },

        //充值
        goRecharge(e) {
            var that = this;
            var storeId = e.currentTarget.dataset.storeid;
            if (app.globalData.isLogin) {
                uni.navigateTo({
                    url: '../recharge/recharge?storeId=' + storeId
                });
            } else {
                that.gotologin();
            }
        },

        goTencentMap(e) {
            var store = e.currentTarget.dataset.info;
            this.goMap(store);
        },

        // 打开地图
        goMap(store) {
            let that = this;
            uni.openLocation({
                latitude: store.lat,
                longitude: store.lon,
                name: store.storeName,
                address: store.address,
                scale: 28
            });
        },

        goDoorDetail() {
            uni.navigateTo({
                url: '../doorDetail/doorDetail'
            });
        },

        //到登录界面
        gotologin() {
            uni.navigateTo({
                url: '../login/login'
            });
        },

        //获取列表数据
        getMainListdata: function (e) {
            var that = this;
            let message = '';
            if (e == 'refresh') {
                //刷新，page变为1
                that.setData({
                    orderlist: [],
                    //列表数组
                    canLoadMore: true,
                    //是否还能加载更多
                    pageindex: 1
                });
                message = '获取中...';
            }
            //if (app.globalData.isLogin)
            {
                http.request(
                    '/member/index/getStoreList',
                    '1',
                    'post',
                    {
                        pageNo: that.pageindex,
                        pageSize: 10,
                        cityName: that.cityName,
                        lat: that.lat,
                        lon: that.lon,
                        name: that.name
                    },
                    app.globalData.userDatatoken.accessToken,
                    message,
                    function success(info) {
                        if (info.code == 0) {
                            let list = info.data.list;
                            let allMarkers = [];
                            if (list.length > 0) {
                                for (let i = 0; i < list.length; i++) {
                                    var title = list[i].storeName;
                                    var lat = list[i].lat;
                                    var lon = list[i].lon;
                                    var storeId = list[i].storeId;
                                    let marker = {
                                        id: storeId,
                                        latitude: lat,
                                        longitude: lon,
                                        callout: {
                                            // 点击marker展示title
                                            content: title
                                        },
                                        fontSize: 20
                                    };
                                    allMarkers.push(marker);
                                    marker = null;
                                }
                                //如果只有一个店 那么直接进入门店主页
                                if (list.length == 1 && that.cityName == '选择城市' && that.name == '') {
                                    // 设置参数
                                    uni.setStorageSync('global_store_id', list[0].storeId);
                                    uni.switchTab({
                                        url: '/pages/index/index'
                                    });
                                } else {
                                    if (info.data.list.length <= info.data.total) {
                                        that.setData({
                                            canLoadMore: false
                                        });
                                    }
                                    if (e == 'refresh') {
                                        that.setData({
                                            MainStorelist: list,
                                            markers: allMarkers,
                                            store: list[0]
                                        });
                                    } else {
                                        let arr = that.MainStorelist;
                                        let arrs = arr.concat(info.data.list);
                                        console.log('arr');
                                        console.log(arr);
                                        let markers = that.markers;
                                        let newMarkers = markers.concat(allMarkers);
                                        that.setData({
                                            MainStorelist: arrs,
                                            markers: newMarkers,
                                            store: arrs[0]
                                        });
                                    }
                                }
                            } else {
                                that.setData({
                                    MainStorelist: [],
                                    markers: [],
                                    store: '',
                                    canLoadMore: false
                                });
                            }
                        } else {
                            uni.showModal({
                                content: info.msg,
                                showCancel: false
                            });
                        }
                    },
                    function fail(info) {}
                );
            }
        },

        //获取首页banner
        getBannerdata: function (e) {
            var that = this;
            //if (app.globalData.isLogin)
            {
                http.request(
                    '/member/index/getBannerList',
                    '1',
                    'get',
                    {},
                    app.globalData.userDatatoken.accessToken,
                    '获取中...',
                    function success(info) {
                        if (info.code == 0) {
                            that.setData({
                                bannershowlist: info.data
                            });
                        }
                    },
                    function fail(info) {}
                );
            }
        },

        // 在需要获取位置的页面的Page函数中定义获取位置的方法
        getLocation: function () {
            let that = this;
            uni.getLocation({
                type: 'gcj02',
                success: function (res) {
                    const latitude = res.latitude;
                    const longitude = res.longitude;
                    that.setData({
                        lat: latitude,
                        lon: longitude
                    });
                    that.getMainListdata('refresh');
                    // 处理位置信息，比如将位置信息显示在页面上
                    // 示例中使用的是util.js中的函数，开发者可以根据需要自行编写
                    //util.showLocation(latitude, longitude)
                },

                fail: function (res) {
                    that.getMainListdata('refresh');
                    // 如果获取位置信息失败，可以处理错误情况
                    //console.log('获取位置失败', res.errMsg)
                }
            });
        },

        call: function (e) {
            // let that = this;
            // var aphoneinfo = e.currentTarget.dataset.info;//获取当前点击的下标
            let that = this;
            var phoneLength = e.currentTarget.dataset.info.length;
            if (phoneLength > 0) {
                if (phoneLength == 11) {
                    uni.makePhoneCall({
                        phoneNumber: e.currentTarget.dataset.info,
                        success: function () {
                            //console.log("拨打电话成功！")
                        },
                        fail: function () {
                            //console.log("拨打电话失败！")
                        }
                    });
                } else {
                    uni.showModal({
                        title: '提示',
                        content: '客服上班时间10：00~23：00\r\n如您遇到问题，建议先查看“使用帮助”！\r\n本店客服微信号：' + e.currentTarget.dataset.info,
                        confirmText: '复制',
                        complete: (res) => {
                            if (res.confirm) {
                                uni.setClipboardData({
                                    data: e.currentTarget.dataset.info,
                                    success: function (res) {
                                        uni.showToast({
                                            title: '微信号已复制到剪贴板！'
                                        });
                                    }
                                });
                            } else if (res.cancel) {
                                //console.log('用户点击取消')
                            }
                        }
                    });
                }
            }
            // if(aphoneinfo.length>0){
            //   //console.log("拨打电话+++")
            //   wx.makePhoneCall({
            //     phoneNumber:aphoneinfo,
            //     success:function () {
            //       //console.log("拨打电话成功！")
            //     },
            //     fail:function () {
            //       //console.log("拨打电话失败！")
            //     }
            //   })
            // }
        },

        //获取列表数据
        getXiaLaListdata: function (e) {
            var that = this;
            //if (app.globalData.isLogin)
            {
                http.request(
                    '/member/index/getStoreList?cityName=' + that.cityName,
                    '1',
                    'get',
                    {
                        cityName: that.cityName
                    },
                    app.globalData.userDatatoken.accessToken,
                    '获取中...',
                    function success(info) {
                        console.info('下拉门店数据===');
                        console.info(info);
                        if (info.code == 0) {
                        } else {
                            uni.showModal({
                                content: '请求服务异常，请稍后重试',
                                showCancel: false
                            });
                        }
                    },
                    function fail(info) {}
                );
            }
        },

        // 搜索框值改变
        onInputChange: function (e) {
            this.setData({
                name: e.detail.value
            });
            this.getMainListdata('refresh');
        },

        // 点击marker展示门店信息
        makertap: function (e) {
            //console.log('makertap+++++++');
            var that = this;
            var storeId = e.markerId;
            that.MainStorelist.map((it) => {
                if (it.storeId === storeId) {
                    that.setData({
                        store: it
                    });
                }
            });
        },

        openDoor(e) {
            var that = this;
            // let aindex = e.currentTarget.dataset.index;
            if (app.globalData.isLogin) {
                uni.navigateTo({
                    url: '../orderDetail/orderDetail?toPage=true'
                });
            } else {
                that.gotologin();
            }
        },

        goUser: function () {
            uni.switchTab({
                url: '/pages/user/user'
            });
        }
    }
};
</script>
<style>
@import './doorList.css';
</style>
